import React from 'react';
import {inject, observer} from 'mobx-react';
import { Browser } from 'weaver-mobile-page'
import { withRouter, HashRouter as Router, Route, Switch } from 'react-router-dom';
import { autorun,toJS} from 'mobx'
import { Tools,SearchBar,Icon,WhiteSpace,PullToRefresh,Popover,Button} from 'weaver-mobile';
import ScrollSelect from '../../public/scrollselect'
import GoalLinkage from './goalLinkage/GoalLinkage'
import MenuList from '../../public/menulist'
import LevelList from '../../public/levellist'
import FoldList from '../../public/foldlist'
import WrMenu from '../../public/menu'
import GoalLevel from './/goalLevel/GoalLevel'
import AlertPage from '../../public/alertPage'
import Tagmanage from '../../public/tagmanage'

const getLabel = Tools.getLabel;
@inject('goalMainStore','goalCommonStore')
@withRouter
@observer
class GoalMain extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      isRight:"",  //是否开启目标模块
      down: true,
      refreshing: false,
      isShowGoal:false,//是否展示公司目标
      goalMainTagBrowserStore:new Browser.Store({ route: '/goalHome/goalMain/'}),
    }
  }

  componentWillMount () {
   
    Tools.callApi({
      url: "/api/workrelate/common/checkHasRigth",
      method: "GET",
      params:  {id:1},
    }).then((data) => {
         if(data.status && data.isRight){
            this.setState({isRight:"1",isShowGoal:data.isShowOrgGoal});
            this.doNext();
        }else{
            this.setState({isRight:"0",isShowGoal:data.isShowOrgGoal});
        }
    })
  }

  doNext = () =>{
    const {goalListAll,condtype,goalCard} = this.props.goalMainStore;
    goalCard({
      condtype,
      doback:()=>{
        goalListAll({});
      }
    })
    let disposer = autorun(() => {
      const { jumpGoalFbMonitor } = this.props.goalMainStore
      if (this.state.jumpGoalFbMonitor != jumpGoalFbMonitor) {
        this.state.jumpGoalFbMonitor = jumpGoalFbMonitor
        if (jumpGoalFbMonitor.id) {
          this.props.history.push("/goalHome/goalDetail?id=" + jumpGoalFbMonitor.id + "&page=3")
          // window.openLink("/goalHome/goalDetail?id=" + jumpGoalFbMonitor.id + "&page=3")
        }
      }
    })

    this.setState({
      disposer
    })
  }

  componentDidMount(){
    // window.addEventListener('scroll', this.handleScroll);
  }

  componentDidUpdate(){
    const{condtype,changeCondType,sortcond,setSortCond} = this.props.goalMainStore;
    const{setSelectViewType} = this.props.goalCommonStore;
    if (condtype && this.props.match.params.condtype != condtype) {
      if (/^\d+$/.test(this.props.match.params.condtype)) {
        let condtype = this.props.match.params.condtype
        changeCondType(condtype)
        if(sortcond == 4){
          setSelectViewType("3")
        }else{
          setSelectViewType(sortcond)
        }
      }
    }
  }

  handleScroll(e) {
    // console.log('浏览器滚动事件');
  }

  componentWillReceiveProps(newProps){
    // let {goalMainStore,goalCommonStore} = this.props;
    // let {condtype,setSortCond} = goalMainStore;
    // let {setSelectViewType} = goalCommonStore;
    // if(condtype != 1){
    //   setSelectViewType("3")
    //   setSortCond(3);
    // }
  }

  
  componentWillUnmount() {
    const { disposer} = this.state
    disposer && disposer()
    this.props.goalMainStore.jumpGoalFbMonitor = null
  }

  /**
   * 加载更多
   */
  showMore = (idx,total,pagenum,cate) =>{
    const {getMoreData} = this.props.goalMainStore
    let params = {};
    params.index = idx;
    params.total = total;
    params.pagenum =  parseInt(pagenum)+1;
    params.cate = cate;
    getMoreData(params);
  }

  /**
   * 分类折叠点击
   */
  onOpenFoldClick = (datetypeid,open) =>{

  }

  onAdvancedSearchBtnClick = () => {
    this.props.history.push("/goalHome/mainAdvancedSearch")
  }

  onCreateNewGoal = (type) => {
    const {currentperiod,canCreate,personCanCreate,condtype} = this.props.goalMainStore;
    if((condtype == 2 || condtype == 8) ){
      if(!canCreate){
        return;
      }
    }else{
      if(!personCanCreate){
        return;
      }
    }
    if(type){
      this.props.history.push("/goalHome/goalAdd?type=" + type +"&period="+currentperiod)
    }else{
      this.props.history.push("/goalHome/goalAdd?period="+currentperiod)
    }

  }

  onGoalItemClick = (goalid) => {
    this.props.history.push("/goalHome/goalDetail?id=" + goalid)
  }

  onSelectClick = (target) =>{
    let {changeCondType,setCondType,goalCard,setIsShowLevel,sortcond} = this.props.goalMainStore
    let {setSelectViewType,setIsOrgGoal} = this.props.goalCommonStore;
    let condType = target.props.path;
    setCondType(condType);
    setIsOrgGoal(condType);
    if(condType && condType == "2"){
      goalCard({condtype:condType,doback:()=>{
        setIsShowLevel(condType)
      }})
      setSelectViewType("4")
    }else if(condType && condType == "8"){
      goalCard({condtype:condType,doback:(len)=>{
        len && len > 0 ? this.setCondType(condType,true) : this.setCondType(condType,false)
      }})
    }else{
      this.setCondType(condType,true)
    }
    this.props.history.push("/goalHome/goalMain/" + condType)
  }

  setCondType = (condType,isRefresh) =>{
    let {changeCondType,sortcond} = this.props.goalMainStore
    let {setSelectViewType} = this.props.goalCommonStore;
    isRefresh ? changeCondType(condType,isRefresh) : changeCondType(condType,false);
    setSelectViewType(sortcond)
  }


  //快速搜索
  onSearchBarBlur = () => {
    const {goalListAll} = this.props.goalMainStore;
    goalListAll({doback:()=>{
      this.setState({refreshing:false})
    }})
  }

  //标签管理组件
  renderTagManage = () => {
    return (
      <Tagmanage />
    )
  }

  //批量标记标签
  onTagBrowserChange = (data) =>{
    const { batchSetTagOperation } = this.props.goalMainStore
    let tagtype = "";
    if (Array.isArray(data)) {   // 点击清除按钮
      tagtype = "3"
    } else {  // 点击确定按钮
      tagtype = "2"
    }

    let tagids = ""
    if (tagtype != "3") {
      tagids = toJS(data).map((d, i) => d.id).join(",")
    }

    batchSetTagOperation({
      tagids,
      tagtype,
      opentagtype: "1",   // 打开标签浏览按钮的方式为批量设置方式
      infos: getLabel(516448, "确定要清除选中数据的所有标签吗？")
    })
  }

  render() { 
      const {goalCommonStore,goalMainStore} = this.props;
      const {datalist,datetype,setCommonParams,sortcond,hasmore,pagenum,itotal,condtype,isShowLevel,searchname,setSearchname,loading,jumpGoalFbMonitor,nowyear,nowmonth,nowseason,currentperiod,currentstatus,changeCondType,condTypeOptions,advancedSearchPopoverVisible,changeAdvancedSearchPopoverVisible,personCanCreate,typeId,orgId,orgTypeList,currentOrgId,canCreate,orgtitle,
          changeShowBatchChoose,showBatchChoose,clearBatchInfo,changeIsBatchChoosed,isBatchChoosed,batchChoose,batchChooseNum,onGoalCheckedChange} = goalMainStore;
      const {viewType,selectViewType,setSelectViewType} = goalCommonStore;
      const {isRight,isShowGoal,goalMainTagBrowserStore} = this.state;
      let newCondType = []
      if(!isShowGoal){
        let arr1 = condTypeOptions.slice(0,condTypeOptions.length-3)
        newCondType = arr1;
      }else{
        newCondType = condTypeOptions;
      }
      if(isRight == ""){
        return <div></div>
      }
      if(isRight == "0"){
        return <AlertPage show={true} icon="wuquanxian" msg={getLabel(509341,"您的系统未开启目标管理模块")} ></AlertPage>
      }
      if(loading){
        goalCommonStore.showLoading()
      }else{
        goalCommonStore.closeLoading()
      }
      //视图类型显示
      let menuType = viewType;
      if(condtype != "1"){
        menuType = viewType.slice(1,3)
      }
      return (
        <div className="workrelate_moblie_goalmain">
         {orgTypeList && orgTypeList.length == 0 && condtype == 8 ? <AlertPage show={true} icon="wuquanxian" msg={getLabel(518694, '暂未设置组织目标')} ></AlertPage>
         : isShowLevel ? <GoalLevel setCommonParams={setCommonParams} condtype={condtype}  onCallBackSuccess={changeCondType} typeId={typeId} orgId={orgId} orgTypeList={orgTypeList} currentOrgId={currentOrgId} orgtitle={orgtitle}/> :
         <div className="main_content  workrelate-swipe">
            <div className="workrelate_moblie_goalmain_top">
                <div className="workrelate_moblie_goalmain_top_left">
                    <MenuList
                      data={menuType}
                      selectKey={selectViewType}
                      onChange={(selectKey) => {
                        setCommonParams("",selectKey,"") 
                        setSelectViewType(selectKey)
                      }}
                      width={30}
                      showMenu={false}
                      showSelectText={false}
                      itemWith={100}
                      paddingHeight={14}
                      paddingWidth={10}
                      xOffset = {10}
                    />
                </div>
             <SearchBar 
                placeholder={getLabel(500351,'请输入关键字') }
                maxLength={7} 
                value={searchname}
                extraButton={[
                    { key: 'advanced', show: <Icon key="filter-o" type="filter-o" /> },
                    {
                      key: 'drop',
                      show: (
                        <Popover
                          mask
                          visible={advancedSearchPopoverVisible}
                          overlay={[
                            <Popover.Item key="1">{getLabel(30884,'标签设置')}</Popover.Item>,
                            <Popover.Item key="2">{getLabel(390705, '批量标记')}</Popover.Item>
                          ]}
                          align={{
                            overflow: { adjustY: 0, adjustX: 0 },
                            offset: [0, 0],
                          }}
                          onSelect={(data) => {
                            changeAdvancedSearchPopoverVisible(false)
                            let key = data.key
                            if (key === "1") {
                              this.props.history.push("/goalHome/goalMain/tagManage")
                            }else if (key === "2") {
                              changeShowBatchChoose(true)
                            }
                          }}
                          onVisibleChange={(advancedSearchPopoverVisible) => {
                            changeAdvancedSearchPopoverVisible(advancedSearchPopoverVisible)
                          }}
                        >
                          <Icon key="ellipsis" type="ellipsis" />
                        </Popover>
                      )
                    }
                  ]}
                showExtraButton
                onChange={(val) => { setSearchname(val)}}
                onBlur={() => { this.onSearchBarBlur() }}
                onExtraButtonClick={(key) => { key === "advanced" && this.onAdvancedSearchBtnClick() }}
                onClear={(val) => setSearchname("")}
            />
              { !showBatchChoose && <div>
                <WhiteSpace size="xs" />
                <GoalLinkage onChange={(value) => setCommonParams(value, "", "")} nowyear={nowyear} nowmonth={nowmonth} nowseason={nowseason} currentperiod={currentperiod} currentstatus={currentstatus} locationKey={new Date().getTime()} orgTypeList={orgTypeList} currentOrgId={currentOrgId} condtype={condtype}></GoalLinkage>
                <WhiteSpace size="md" />

              </div>}
                {
                  showBatchChoose &&
                  <div className="batch-choose-wrapper">
                    <span
                      onClick={() => {
                        clearBatchInfo()
                      }}
                    >
                      {getLabel(31129, "取消")}
                    </span>
                    <span>
                      {getLabel(513668, "已选择{num}条数据").replace("{num}", batchChooseNum)}
                    </span>
                    <span
                      style={{ color: isBatchChoosed && "#55B1F9" }}
                      onClick={() => {
                        changeIsBatchChoosed(!isBatchChoosed)
                        batchChoose(!isBatchChoosed)
                      }}
                    >
                      {getLabel(556, "全选")}
                    </span>
                  </div>
                }
            </div>
            <PullToRefresh
              damping={70}
              distanceToRefresh={35}
              style={{
                // height: window.innerHeight - 140,
                // height: document.documentElement.clientHeight,
                // height: "auto",
                overflowY: 'auto',
              }}
              indicator={this.state.down ? {} : { deactivate: '上拉可以刷新' }}
              direction={this.state.down ? 'down' : 'up'}
              refreshing={this.state.refreshing}
              onRefresh={() => {
                this.setState({ refreshing: true })
                this.onSearchBarBlur()
                // setTimeout(() => {
                //   this.setState({ refreshing: false })
                // }, 1000)
              }}
            >
           {!loading &&datalist && datalist.length == 0 && datetype && datetype == 0 ?<AlertPage show={true} icon="no-data" msg={getLabel(83553, "暂无数据")} ></AlertPage> :
            <div className="workrelate_moblie_goalmain_content" >
              {
                 datetype && datetype.length == 0 ?
                <LevelList 
                  key={ Math.random(1) }
                  headColor={ "#000" }
                  bgColor={"#fff"}
                  showseq={ true }
                  data={ datalist }
                  hasMore={ hasmore }
                  getMore={ () => this.showMore(0,itotal,pagenum,"0") }
                  showGetMore={ true }
                  onItemClick={ (dataid) => { this.onGoalItemClick(dataid) } }
                  showCheckbox={showBatchChoose}
                  onCheckedChange={onGoalCheckedChange}
                //  getChildren={ (dataid) => { this.getTaskChildren(dataid) } }
                  // bottomActionTitle={ "新建任务" }
                //  onBottomActionClick={ () => { this.onCreateNewTask() } }
                >
                </LevelList>:
                 datetype && datetype.length > 0 && datetype.map((d,i)=>{
                    return(
                      <div key={ Math.random(1) }>
                        <FoldList
                          id={d.id}
                          sticky={ true }
                          headColor={ d.color }
                          headIconclass={ "serial-node" }
                          headIconsize={ "lg" }
                          headIconStyle={{ width: 25 }}
                          count={ d.total }
                          title={ d.name }
                          showseq={ true }
                          // open={ d.isopen }
                          open={ true }
                          data={ datalist.filter((dt, i) => { return dt.treetype == "m" + d.id }) }
                          hasMore={ d.hasmore }
                          getMore={ () => this.showMore(i,d.total,d.pagenum,d.id) }
                          showGetMore={ true }
                          onOpenFoldClick={ (open) => { this.onOpenFoldClick(d.id, open)}}
                          onItemClick={ (dataid) => { this.onGoalItemClick(dataid) }}
                          onAddIconClick={ () => { this.onCreateNewGoal(d.id) } }
                          hasRight={condtype == 9 ? false : (condtype == 8 ? canCreate:personCanCreate)}
                          showCheckbox={showBatchChoose}
                          onCheckedChange={onGoalCheckedChange}
                        ></FoldList>
                      </div>
                    )
                  })
                }
            </div>      
            }  
            </PullToRefresh>   
          </div>
          }
          <div className="workrelate_moblie_goalmain_bottom">
            {
              showBatchChoose ?
                <div className="batch-tag">
                  <Button
                    type="primary"
                    disabled={batchChooseNum == 0}
                    onClick={() => {
                      let goalMainTagBrowserStore = new Browser.Store({ route: '/goalHome/goalMain/' + condtype })
                      this.setState({
                        goalMainTagBrowserStore
                      },()=>{
                        this.props.history.push(goalMainTagBrowserStore.path)
                      })
                    }}
                  >
                    {getLabel(390705, '批量标记')}
                  </Button>
                  <div style={{ display: "none" }}>
                    <Browser
                      store={goalMainTagBrowserStore}
                      isSingle={false}
                      type={"wrltag"}
                      valueArray={[]}
                      onChange={(...arg) => {
                        this.onTagBrowserChange(arg[2])
                      }}
                    />
                  </div>
                </div> :
                <WrMenu
                  data={newCondType}
                  onSelect={(value) => this.onSelectClick(value)}
                  iconType={condtype == 9 ? "" : (condtype == 2 || condtype == 8 ? (canCreate ? "plus" : "") : (personCanCreate ? "plus" : ""))}
                  onIconClick={() => this.onCreateNewGoal()}
                  currentkey={condtype}
                />
            }
          </div>
          <Switch>
            <Route name='taskMainTagManage' breadcrumbName={getLabel(30884, '标签设置')} path={'/goalHome/goalMain/tagManage'} render={() => { return this.renderTagManage() }} />
          </Switch>
        </div>
      )
    }
  }
  
  export default GoalMain;